package com.example.compose

import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.FileUtils
import android.os.storage.StorageManager
import android.provider.DocumentsContract
import android.webkit.MimeTypeMap
import androidx.activity.compose.setContent
import androidx.annotation.RequiresApi
import androidx.compose.animation.core.*
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.draw.scale
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.core.content.FileProvider
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.rememberAsyncImagePainter
import com.example.compose.retrofit.updataApp.CheckUpdateActivity
import com.example.compose.ui.theme.StarLightsTheme
import com.example.compose.utils.BitmapUtils
import com.example.compose.utils.LogUtil
import com.example.compose.utils.ShareManager
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream
import java.net.URI
import kotlin.math.roundToInt
import kotlin.random.Random

class GreetingCardActivity : BaseComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            StarLightsTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    GreetingCard(this,lifecycle)
                }
                // 是否全屏显示图片
//                var isShowImageFullScreen by remember {
//                    mutableStateOf(false)
//                }
//                Column(
//                    modifier = Modifier
//                        .fillMaxSize()
//                        .background(Color.White)
//                        .navigationBarsPadding()
//                ) {
//                    Button(onClick = { isShowImageFullScreen = true }) {
//                        Text(text = "显示图片")
//                    }
//                }
//                if (isShowImageFullScreen) {
//                    FullScreenImage(url = "https://profile.csdnimg.cn/A/0/9/1_sinat_38184748") {
//                        // 点击图片关闭显示
////                        isShowImageFullScreen = false
//                    }
//                }
            }
        }
    }
}
fun onClick(){

}

@Composable
fun FullScreenImage(
    modifier: Modifier = Modifier,
    url: String,
    onClick: () -> Unit = {}
) {

    var offset by remember { mutableStateOf(Offset.Zero) }
    var rotateAngle by remember { mutableStateOf(0f) }
    var scale by remember { mutableStateOf(1f) }

    Surface(
        color = Color.DarkGray,
        modifier = modifier
            .fillMaxSize()
//            .pointerInput(Unit) {
//                detectTapGestures(
//                    onDoubleTap = {
//                        scale = 1f
//                        rotateAngle = 0f
//                        offset = Offset.Zero
//                    },
//                    onTap = {
//                        onClick()
//                    }
//                )
//            }
    ) {
        Image(
            painter = rememberAsyncImagePainter(url),
            contentDescription = "",
            modifier = Modifier
                .wrapContentSize()
                .rotate(rotateAngle) // 需要注意offset与rotate的调用先后顺序
                .scale(
                    if (scale > 4) {
                        scale = 4f
                        4f
                    } else scale
                )
                .offset {
                    IntOffset(offset.x.roundToInt(), offset.y.roundToInt())
                }
                .background(Color.White)
                .pointerInput(Unit) {
                    detectTransformGestures(
                        panZoomLock = true,
                        onGesture = { _: Offset, dragAmount: Offset, zoom: Float, rotation: Float ->
                            LogUtil.d("detectTransformGestures dragAmount$dragAmount zoom$zoom rotation$rotation")
                            offset += dragAmount
                            scale *= zoom
                            rotateAngle += rotation
                        }
                    )
                }

        )
        Text(text = "放大比例$scale")
    }
}

@Preview
@Composable
fun TwoTexts() {
    Row(modifier = Modifier.height(IntrinsicSize.Min)) { // I'm here
        Text(
            modifier = Modifier
                .weight(1f)
                .padding(horizontal = 4.dp)
                .wrapContentWidth(Alignment.Start),
            text = "text1"
        )

        Divider(color = Color.Black, modifier = Modifier
            .fillMaxHeight()
            .width(1.dp))
        Text(
            modifier = Modifier
                .weight(1f)
                .padding(horizontal = 4.dp)
                .wrapContentWidth(Alignment.End),
            text = "text2text2text2text2text2text2text2text2text2text2text2text2"
        )
    }
}
@Preview
@Composable
fun Test(){
  Row (){
      Image( modifier = Modifier.fillMaxWidth(),
          painter = painterResource(id = R.mipmap.home_bg_2),
          contentDescription = null)
  }
}


@Composable
fun GreetingCard(
    context: Context,
    lifecycle:Lifecycle,
    testViewModel: TestViewModel = viewModel()
) {
    val collectAsState = testViewModel.test.collectAsState()

    var carryOn by remember { mutableStateOf(true) }
    var progress by remember{ mutableStateOf(0f)}
    val angle = remember { Animatable(0f, Float.VectorConverter) }

    val scope = rememberCoroutineScope()
    LaunchedEffect(scope) {
        async {
            angle.animateTo(359f,
                infiniteRepeatable(
                    animation = tween(3000, easing = LinearEasing),
                    repeatMode = RepeatMode.Restart,
                )
            )
        }
        async {
            testViewModel.test.collect{
                it.data?.let { data->
                    val intent = Intent(context, CheckUpdateActivity::class.java)
                    data.app_version_number
                    intent.putExtra("data",data)
                    context.startActivity(intent)
                }
            }
        }
    }
    Box(modifier = Modifier
        .fillMaxSize()
        .clickable {
            carryOn = !carryOn
            scope.launch {
                if (carryOn) {
                    angle.animateTo(
                        angle.value + 359f, infiniteRepeatable(
                            animation = tween(3000, easing = LinearEasing),
                            repeatMode = RepeatMode.Restart,
                        )
                    )
                } else {
                    angle.stop()
                }
            }
        }, contentAlignment= Alignment.Center){
        Column(horizontalAlignment = Alignment.CenterHorizontally) {
            Slider(
                value = progress,
                colors = SliderDefaults.colors(
                    thumbColor = Color.White, // 圆圈的颜色
                    activeTrackColor = Color(0xFF0079D3)
                ),
                onValueChange = {
                    progress = it
                },
            )
            Surface(shape = CircleShape, border = BorderStroke(5.dp, Color.Gray) ){
                Image(painter = painterResource(id = R.mipmap.home_bg_2), modifier = Modifier
                    .size(360.dp)
                    .rotate(angle.value),
                    contentScale = ContentScale.Crop,
                    contentDescription = "")
            }
            Button(onClick = {
                ShareManager.shareText(context,"❤❤❤❤❤")
            }) {
                Text(text = stringResource(id = R.string.share))
            }
            Button(onClick = {
                BitmapUtils().saveToLocalPNG(BitmapFactory.decodeResource(context.resources,R.mipmap.home_bg_2))?.let {
                    ShareManager.shareImage(context, it)
                }
            }) {
                Text(text = stringResource(id = R.string.share))
            }
            Button(onClick = {
                scope.launch {
                    collectAsState.value.data?.app_url?.let { url ->
                    }
                }
            }) {
                collectAsState.value.data?.app_url?.let { Text(text = it) }
            }
        }

    }

}

fun uriToFile(context: Context, uri: Uri): File {
    return File(URI(uri.toString()))
}

fun uriToFileR(context: Context, uri: Uri): File? {
    try {
        val docId = try {
            DocumentsContract.getDocumentId(uri)
        }catch (e:Exception){
            try {
                DocumentsContract.getTreeDocumentId(uri)
            }catch (e:Exception){""}
        }
        val split = docId.split(":")
        val type = split[0]
        if(type.equals("primary",true)){
            return runCatching { File("${Environment.getExternalStorageDirectory()}/${split[1]}") }.getOrNull()
        }else{
            val manager = context.getSystemService(Context.STORAGE_SERVICE) as StorageManager
            val storageVolumeClazz = Class.forName("android.os.storage.StorageVolume")
            val getVolumeList = manager.javaClass.getMethod("getVolumeList")
            val getUuid = storageVolumeClazz.getMethod("getUuid")
            val getState = storageVolumeClazz.getMethod("getState")
            val getPath = storageVolumeClazz.getMethod("getPath")
            val result = getVolumeList.invoke(manager)
            result?.let {
                val length = java.lang.reflect.Array.getLength(it)
                for (i in 0 until length){
                    val ele = java.lang.reflect.Array.get(it,i)
                    if(Environment.MEDIA_MOUNTED == getState.invoke(ele) || Environment.MEDIA_MOUNTED_READ_ONLY == getState.invoke(ele)){
                        val uuid = getUuid.invoke(ele) as? String
                        if(uuid == type){
                            return runCatching { File("${getPath.invoke(ele)}/${split[1]}") }.getOrNull()
                        }
                    }
                }
            }
        }
    }catch (e:Exception){

    }
    return null
}

@RequiresApi(Build.VERSION_CODES.Q)
private fun uriToFileQ(context: Context, uri: Uri): File? =
    if (uri.scheme == ContentResolver.SCHEME_FILE)
        File(requireNotNull(uri.path))
    else if (uri.scheme == ContentResolver.SCHEME_CONTENT) {
        //把文件保存到沙盒
        val contentResolver = context.contentResolver
        val displayName = "${System.currentTimeMillis()}${Random.nextInt(0, 9999)}.${
            MimeTypeMap.getSingleton()
                .getExtensionFromMimeType(contentResolver.getType(uri))}"
        val ios = contentResolver.openInputStream(uri)
        if (ios != null) {
            File("${context.cacheDir.absolutePath}/$displayName")
                .apply {
                    val fos = FileOutputStream(this)
                    FileUtils.copy(ios, fos)
                    fos.close()
                    ios.close()
                }
        } else null
    } else null


fun install(context: Context,apk:File){
    val intent = Intent(Intent.ACTION_VIEW)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        //注意第二个参数，要保持和manifest中android:authorities的值相同
        val uri = FileProvider.getUriForFile(
            context,
            context.packageName.toString() + ".fileProvider",
            apk
        )
        intent.setDataAndType(uri, "application/vnd.android.package-archive")
    } else {
        intent.setDataAndType(Uri.fromFile(apk), "application/vnd.android.package-archive")
    }
    try {
        context.startActivity(intent)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}